package com.winit.openapi.es.proxy;


import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.List;

import org.elasticsearch.common.transport.InetSocketTransportAddress;

public class TransportAddresses {

    static final String DELIMETER = ":";

    private final String[] nodes;

    TransportAddresses(String[] nodes){
        if (nodes == null) {
            throw new IllegalArgumentException("Elasticsearch hosts cannot be null");
        }
        if (nodes.length == 0) {
            throw new IllegalArgumentException("At least one Elasticsearch host must be specified");
        }

        this.nodes = nodes;
    }

    public InetSocketTransportAddress[] getAddresses() {
        List<InetSocketTransportAddress> result = new LinkedList<InetSocketTransportAddress>();

        for (String node : nodes) {
            InetSocketTransportAddress transportAddress = transformToInetAddress(node);
            result.add(transportAddress);
        }

        return result.toArray(new InetSocketTransportAddress[] {});
    }

    private InetSocketTransportAddress transformToInetAddress(String node) {
        String[] hostAndPort = node.split(DELIMETER);
        if (hostAndPort.length != 2) {
            throw new IllegalArgumentException("Incorrect Elasticsearch node format, should follow {host}" + DELIMETER
                                               + "{port} pattern");
        }
        String hostname = hostname(hostAndPort[0]);
        return new InetSocketTransportAddress(new InetSocketAddress(hostname, port(hostAndPort[1])));
    }

    private String hostname(String input) {
        return input.trim();
    }

    private int port(String input) {
        return Integer.parseInt(input.trim());
    }
}
